import React, { useEffect, useState } from "react";
import { Link, useLocation } from "react-router-dom";

// styled-component
import { Nav,Icon } from "../../pages/main/Main.style";

// navbar 配置数组
const navbarConfig = [
  {
    id:'community',
    text:'社区',
    url:'/community',
    selectedIcon:'selected',
    noSelectedIcon:'noSelected'
  },
  {
    id:'mall',
    text:'商城',
    url:'/mall',
    selectedIcon:'selected',
    noSelectedIcon:'noSelected'
  },
  {
    id:'main',
    text:'理想ONE',
    url:'/main',
    selectedIcon:'selected',
    noSelectedIcon:'noSelected'
  },
  {
    id:'message',
    text:'消息',
    url:'/message',
    selectedIcon:'selected',
    noSelectedIcon:'noSelected'
  },
  {
    id:'me',
    text:'我的',
    url:'/me',
    selectedIcon:'selected',
    noSelectedIcon:'noSelected'
  },
]

// 自定义 hook：获取 url 中的一级path
function useGetFirstPath() {
  const {pathname} = useLocation()
  console.log(pathname);
  if(pathname == "/") {
    return ''
  }
  const iconText = pathname.match(/^\/\w+/)[0].slice(1)
  
  return iconText
}


export default function Navbar(props) {

  // todo:创建 store，使用 store 中的数据
  const [selected,setSelected] = useState('main')
  const iconText = useGetFirstPath()
  console.log(iconText)
  
  

  useEffect(() => {
    setSelected(iconText)
  },[iconText])

  return (
    <Nav>
      {
        navbarConfig.map(item => {
          const {id,text,url,selectedIcon,noSelectedIcon} = item;
          return (
            <div key={id}>
              <Link to={url} className="link">
                <Icon url={selected == id? selectedIcon : noSelectedIcon}>{selected == id? selectedIcon : noSelectedIcon}</Icon>
                <div>{text}</div>
              </Link>
            </div>
          )
        })
      }
      
    </Nav>
  )
}